package com.taoyige;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.Properties;
import java.util.UUID;

import org.json.JSONObject;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.CacheManager;

import com.taoyige.api.ApiClient;
import com.taoyige.bean.Address;
import com.taoyige.bean.AddressList;
import com.taoyige.bean.ClientInfo;
import com.taoyige.bean.Goods;
import com.taoyige.bean.Notice;
import com.taoyige.bean.Order;
import com.taoyige.bean.OrderList;
import com.taoyige.bean.Result;
import com.taoyige.bean.User;
import com.taoyige.common.AlipaySignUtils;
import com.taoyige.common.ImageUtils;
import com.taoyige.common.StringUtils;
import com.taoyige.common.UIHelper;

/**
 * 全局应用程序类：用于保存和调用全局应用配置及访问网络数据
 * @author peter
 * @version 1.0
 * @date 2014-11-12
 */
public class AppContext extends Application {
	
	public static final int NETTYPE_WIFI = 0x01;
	public static final int NETTYPE_CMWAP = 0x02;
	public static final int NETTYPE_CMNET = 0x03;
	
	public static final int PAGE_SIZE =8;//默认分页大小
	private static final int CACHE_TIME = 60*60000;//缓存失效时间
	
	private boolean login = false;	//登录状态
	private String loginUid = "0";	//登录用户的id
	
	//public Hashtable<String, Object> session = new Hashtable<String, Object>();
	private Hashtable<String, Object> memCacheRegion = new Hashtable<String, Object>();
	
	private String saveImagePath;//保存图片路径
	
	private Handler unLoginHandler = new Handler(){
		public void handleMessage(Message msg) {
			if(msg.what == 1){
				UIHelper.ToastMessage(AppContext.this, getString(R.string.msg_login_error));
				//UIHelper.showLoginDialog(AppContext.this);
			}
		}		
	};
	
	@Override
	public void onCreate() {
		super.onCreate();
        //注册App异常崩溃处理器
        Thread.setDefaultUncaughtExceptionHandler(AppException.getAppExceptionHandler());
        
        init();
	}
	
	/** 获取省市县数据*/
	public JSONObject getLocation(InputStream inputStream) throws AppException{
		return ApiClient.getLocation(this,inputStream);
	}

	/** 获取首页商品数据*/
	public Goods getGoodsIndex() throws AppException{
		return ApiClient.goodsIndex(this);
	}
	
	/** 获取首页即将开始数据*/
	public Goods getGoodsCommingSoon() throws AppException{
		return ApiClient.goodsCommingSoon(this);
	}
	
	/** 保存用户信息*/
	public User userAdd(User user) throws AppException{
		return ApiClient.userAdd(this, user);
	}
	
	/** 获取用户详情数据*/
	public User getUserInfo(String uid) throws AppException{
		return ApiClient.userInfo(this,uid);
	}
	
	/** 获取商品详情数据*/
	public Goods getGoodsDetail(Long goodsId) throws AppException{
		return ApiClient.goodsDetail(this,goodsId);
	}
	
	/** 获取地址数据*/
	public AddressList getAddrList(String uid) throws AppException{
		return ApiClient.addList(this,uid);
	}
	
	/** 设置默认地址*/
	public Address setAddressDefault(String id,String uid) throws AppException{
		return ApiClient.setAddressDefault(this,id,uid);
	}
	
	/** 删除地址*/
	public Address delAddress(String uid,String id) throws AppException{
		return ApiClient.delAddress(this,uid,id);
	}
	
	/** 获取地址数据*/
	public Address getAddrDefault(String uid) throws AppException{
		return ApiClient.addrDefault(this,uid);
	}
	
	/** 更新地址数据*/
	public Address addrUpdate(Address addr) throws AppException{
		return ApiClient.addrUpdate(this, addr);
	}
	/** 插入地址数据*/
	public Address addrAdd(Address addr) throws AppException{
		return ApiClient.addrAdd(this, addr);
	}
	
	/** 获取用户购买权限*/
	public Address getGoodsBuyStatus(String uid,String id) throws AppException{
		return ApiClient.getGoodsBuyStatus(this,uid,id);
	}
	
	/** 获取客户端的信息*/
	public ClientInfo getUserAgentInfo(){
		return ApiClient.getUserAgentInfo(this);
	}
	
	/** 获取上传客户端的信息*/
	public Address uploadUserAgentInfo(ClientInfo clientInfo) throws AppException{
		return ApiClient.uploadUserAgentInfo(this,clientInfo);
	}
	
	/**
	 * 获取未付款订单列表
	 * @param uid
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public Order getOrderDetail(String id,String uid) throws AppException {
		Order order = null;
		if(isNetworkConnected() ) {
			try{
				order = ApiClient.orderDetail(this, id,uid );
			}catch(AppException e){
					e.printStackTrace();
			}
		} else {
			if(order == null)
				order = new Order();
		}
		return order;
	}
	
	/**
	 * 获取未付款订单列表
	 * @param uid
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public OrderList getUnpaidOrderList(String uid, int pageIndex, boolean isRefresh) throws AppException {
		OrderList list = null;
		String key = "orderlist_unpaid_"+uid+"_"+pageIndex+"_"+PAGE_SIZE;		
		//if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)){
		if(isNetworkConnected() ) {
			try{
				list = ApiClient.orderUnPaidList(this, uid, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (OrderList)readObject(key);
				if(list == null)
					throw e;
			}
		} else {
			list = (OrderList)readObject(key);
			if(list == null)
				list = new OrderList();
		}
		return list;
	}
	
	
	
	/**
	 * 获取已付款订单列表
	 * @param uid
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public OrderList getPaidOrderList(String uid, int pageIndex, boolean isRefresh) throws AppException {
		OrderList list = null;
		String key = "orderlist_paid_"+uid+"_"+pageIndex+"_"+PAGE_SIZE;		
		//if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)){
		if(isNetworkConnected() ) {
			try{
				list = ApiClient.orderPaidList(this, uid, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (OrderList)readObject(key);
				if(list == null)
					throw e;
			}
		} else {
			list = (OrderList)readObject(key);
			if(list == null)
				list = new OrderList();
		}
		return list;
	}
	
	/**
	 * 获取已完成订单列表
	 * @param uid
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public OrderList getCompleteOrderList(String uid, int pageIndex, boolean isRefresh) throws AppException {
		OrderList list = null;
		String key = "orderlist_complete_"+uid+"_"+pageIndex+"_"+PAGE_SIZE;		
		//if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)){
		if(isNetworkConnected() ) {
			try{
				list = ApiClient.orderCompleteList(this, uid, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (OrderList)readObject(key);
				if(list == null)
					throw e;
			}
		} else {
			list = (OrderList)readObject(key);
			if(list == null)
				list = new OrderList();
		}
		return list;
	}
	
	
	/** 保存订单数据*/
	public Order orderAdd(Order order) throws AppException{
		return ApiClient.orderAdd(this, order);
	}
	
	/** 更新订单为已付款*/
	public Order orderPaid(String orderId) throws AppException{
		return ApiClient.orderPaid(this, orderId);
	}
	
	/** 取消订单*/
	public Order orderCancel(String orderId,String uid) throws AppException{
		return ApiClient.orderCancel(this, orderId,uid);
	}
	
	/** 确认收货*/
	public Order orderRecepit(String orderId,String uid) throws AppException{
		return ApiClient.orderRecepit(this, orderId,uid);
	}
	
	/**
	 * 初始化
	 */
	private void init(){
		//设置保存图片的路径
		saveImagePath = getProperty(AppConfig.SAVE_IMAGE_PATH);
		if(StringUtils.isEmpty(saveImagePath)){
			setProperty(AppConfig.SAVE_IMAGE_PATH, AppConfig.DEFAULT_SAVE_IMAGE_PATH);
			saveImagePath = AppConfig.DEFAULT_SAVE_IMAGE_PATH;
		}
	}
	
	/**
	 * 检测当前系统声音是否为正常模式
	 * @return
	 */
	public boolean isAudioNormal() {
		AudioManager mAudioManager = (AudioManager)getSystemService(AUDIO_SERVICE); 
		return mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL;
	}
	
	/**
	 * 应用程序是否发出提示音
	 * @return
	 */
	public boolean isAppSound() {
		return isAudioNormal() && isVoice();
	}
	
	/**
	 * 是否发出提示音
	 * @return
	 */
	public boolean isVoice()
	{
		String perf_voice = getProperty(AppConfig.CONF_VOICE);
		//默认是开启提示声音
		if(StringUtils.isEmpty(perf_voice))
			return true;
		else
			return StringUtils.toBool(perf_voice);
	}
	
	/**
	 * 设置是否发出提示音
	 * @param b
	 */
	public void setConfigVoice(boolean b)
	{
		setProperty(AppConfig.CONF_VOICE, String.valueOf(b));
	}
	
	/**
	 * 是否启动检查更新
	 * @return
	 */
	public boolean isCheckUp()
	{
		String perf_checkup = getProperty(AppConfig.CONF_CHECKUP);
		//默认是开启
		if(StringUtils.isEmpty(perf_checkup))
			return true;
		else
			return StringUtils.toBool(perf_checkup);
	}
	
	/**
	 * 设置启动检查更新
	 * @param b
	 */
	public void setConfigCheckUp(boolean b)
	{
		setProperty(AppConfig.CONF_CHECKUP, String.valueOf(b));
	}
	
	/**
	 * 检测网络是否可用
	 * @return
	 */
	public boolean isNetworkConnected() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		return ni != null && ni.isConnectedOrConnecting();
	}

	/**
	 * 获取当前网络类型
	 * @return 0：没有网络   1：WIFI网络   2：WAP网络    3：NET网络
	 */
	public int getNetworkType() {
		int netType = 0;
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		if (networkInfo == null) {
			return netType;
		}		
		int nType = networkInfo.getType();
		if (nType == ConnectivityManager.TYPE_MOBILE) {
			String extraInfo = networkInfo.getExtraInfo();
			if(!StringUtils.isEmpty(extraInfo)){
				if (extraInfo.toLowerCase().equals("cmnet")) {
					netType = NETTYPE_CMNET;
				} else {
					netType = NETTYPE_CMWAP;
				}
			}
		} else if (nType == ConnectivityManager.TYPE_WIFI) {
			netType = NETTYPE_WIFI;
		}
		return netType;
	}
	
	/**
	 * 判断当前版本是否兼容目标版本的方法
	 * @param VersionCode
	 * @return
	 */
	public static boolean isMethodsCompat(int VersionCode) {
		int currentVersion = android.os.Build.VERSION.SDK_INT;
		return currentVersion >= VersionCode;
	}
	
	/**
	 * 获取App安装包信息
	 * @return
	 */
	public PackageInfo getPackageInfo() {
		PackageInfo info = null;
		try { 
			info = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {    
			e.printStackTrace(System.err);
		} 
		if(info == null) info = new PackageInfo();
		return info;
	}
	
	/**
	 * 获取App唯一标识
	 * @return
	 */
	public String getAppId() {
		String uniqueID = getProperty(AppConfig.CONF_APP_UNIQUEID);
		if(StringUtils.isEmpty(uniqueID)){
			uniqueID = UUID.randomUUID().toString();
			setProperty(AppConfig.CONF_APP_UNIQUEID, uniqueID);
		}
		return uniqueID;
	}
	
	
	/**
	 * 设置是是否Https登录
	 * @param b
	 */
	public void setConfigHttpsLogin(boolean b)
	{
		setProperty(AppConfig.CONF_HTTPS_LOGIN, String.valueOf(b));
	}
	
	/**
	 * 清除保存的缓存
	 */
	public void cleanCookie()
	{
		removeProperty(AppConfig.CONF_COOKIE);
	}
	
	/**
	 * 判断缓存数据是否可读
	 * @param cachefile
	 * @return
	 */
	private boolean isReadDataCache(String cachefile)
	{
		return readObject(cachefile) != null;
	}
	
	/**
	 * 判断缓存是否存在
	 * @param cachefile
	 * @return
	 */
	private boolean isExistDataCache(String cachefile)
	{
		boolean exist = false;
		File data = getFileStreamPath(cachefile);
		if(data.exists())
			exist = true;
		return exist;
	}
	
	/**
	 * 判断缓存是否失效
	 * @param cachefile
	 * @return
	 */
	public boolean isCacheDataFailure(String cachefile)
	{
		boolean failure = false;
		File data = getFileStreamPath(cachefile);
		if(data.exists() && (System.currentTimeMillis() - data.lastModified()) > CACHE_TIME)
			failure = true;
		else if(!data.exists())
			failure = true;
		return failure;
	}
	
	/**
	 * 清除app缓存
	 */
	public void clearAppCache()
	{
		//清除webview缓存
		File file = CacheManager.getCacheFileBaseDir();  
		if (file != null && file.exists() && file.isDirectory()) {  
		    for (File item : file.listFiles()) {  
		    	item.delete();  
		    }  
		    file.delete();  
		}  		  
		deleteDatabase("webview.db");  
		deleteDatabase("webview.db-shm");  
		deleteDatabase("webview.db-wal");  
		deleteDatabase("webviewCache.db");  
		deleteDatabase("webviewCache.db-shm");  
		deleteDatabase("webviewCache.db-wal");  
		//清除数据缓存
		clearCacheFolder(getFilesDir(),System.currentTimeMillis());
		clearCacheFolder(getCacheDir(),System.currentTimeMillis());
		clearCacheFolder(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/taoyige"),System.currentTimeMillis());
		//清楚oauth信息
		AppConfig.clearOauthAll(getApplicationContext());
		
		//2.2版本才有将应用缓存转移到sd卡的功能
		/*
		if(isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)){
			clearCacheFolder(MethodsCompat.getExternalCacheDir(this),System.currentTimeMillis());
		}*/
		
		
		
		//清除编辑器保存的临时内容
		Properties props = getProperties();
		for(Object key : props.keySet()) {
			String _key = key.toString();
			if(_key.startsWith("temp"))
				removeProperty(_key);
		}
	}	
	
	/**
	 * 清除缓存目录
	 * @param dir 目录
	 * @param numDays 当前系统时间
	 * @return
	 */
	private int clearCacheFolder(File dir, long curTime) {          
	    int deletedFiles = 0;         
	    if (dir!= null && dir.isDirectory()) {             
	        try {                
	            for (File child:dir.listFiles()) {    
	                if (child.isDirectory()) {              
	                    deletedFiles += clearCacheFolder(child, curTime);          
	                }  
	                if (child.lastModified() < curTime) {     
	                    if (child.delete()) {                   
	                        deletedFiles++;           
	                    }    
	                }    
	            }             
	        } catch(Exception e) {       
	            e.printStackTrace();    
	        }     
	    }       
	    return deletedFiles;     
	}
	
	/**
	 * 将对象保存到内存缓存中
	 * @param key
	 * @param value
	 */
	public void setMemCache(String key, Object value) {
		memCacheRegion.put(key, value);
	}
	
	
	
	/**
	 * 保存对象
	 * @param ser
	 * @param file
	 * @throws IOException
	 */
	public boolean saveObject(Serializable ser, String file) {
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try{
			fos = openFileOutput(file, MODE_PRIVATE);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(ser);
			oos.flush();
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}finally{
			try {
				oos.close();
			} catch (Exception e) {}
			try {
				fos.close();
			} catch (Exception e) {}
		}
	}
	
	/**
	 * 读取对象
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public Serializable readObject(String file){
		if(!isExistDataCache(file))
			return null;
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try{
			fis = openFileInput(file);
			ois = new ObjectInputStream(fis);
			return (Serializable)ois.readObject();
		}catch(FileNotFoundException e){
		}catch(Exception e){
			e.printStackTrace();
			//反序列化失败 - 删除缓存文件
			if(e instanceof InvalidClassException){
				File data = getFileStreamPath(file);
				data.delete();
			}
		}finally{
			try {
				ois.close();
			} catch (Exception e) {}
			try {
				fis.close();
			} catch (Exception e) {}
		}
		return null;
	}
	

	/**
	 * 用户是否登录
	 * @return
	 */
	public boolean isLogin() {
		return login;
	}
	
	/**
	 * 获取登录用户id
	 * @return
	 */
	public String getLoginUid() {
		return this.loginUid;
	}
	
	/**
	 * 用户注销
	 */
	public void logout() {
		ApiClient.cleanCookie();
		this.cleanCookie();
		this.cleanLoginInfo();
	}
	
	/**
	 * 未登录的处理
	 */
	public Handler getUnLoginHandler() {
		return this.unLoginHandler;
	}
	
	/**
	 * 初始化用户登录信息
	 * @throws AppException 
	 */
	public void initLoginInfo() throws AppException {
		User loginUser = getLoginInfo();
		if(loginUser!=null &&!StringUtils.isEmpty(loginUser.getId())){
			this.loginUid = loginUser.getId();
			this.login = true;
		}else{
			ApiClient.cleanCookie();
			this.cleanCookie();
			this.loginUid = "0";
			this.login = false;
		}
	}
	
	/**
	 * 用户登录验证
	 * @return
	 * @throws AppException
	 */
	public User loginVerify() throws AppException {
		//TODO oauth授权登陆
		return  null;
	}
	
	/**
	 * 保存登录信息
	 * @param username
	 * @param pwd
	 */
	public boolean saveLoginInfo(final User u) {
		try {
			//user.setId("4-oLdmltx7_xzeFYKU7r2-F1PvPOEE");
			final User user=getUserInfo(u.getId());
			if(user!=null&&user.getResult().getErrorCode()==200&&user.getId()!=null){
				Log.d("user_info", "user aleady exists!");
				this.loginUid = user.getId();
				this.login = true;
				setProperties(new Properties(){{
					setProperty("user.uid", String.valueOf(user.getId()));
					setProperty("user.pid", String.valueOf(user.getPid()));
					setProperty("user.puid", String.valueOf(user.getpUserID()));
					setProperty("user.name", user.getUserName());
					setProperty("user.pname", user.getpUserName());
					setProperty("user.avatar",user.getThumbUrl());//用户头像-文件名
				}});	
			}else{
				final User nu=userAdd(u);
				if(nu!=null&&nu.getResult().getErrorCode()==200&&nu.getId()!=null)
					Log.d("user_info","user created!");
				this.loginUid = nu.getId();
				this.login = true;
				setProperties(new Properties(){{
					setProperty("user.uid", String.valueOf(nu.getId()));
					setProperty("user.pid", String.valueOf(nu.getPid()));
					setProperty("user.puid", String.valueOf(nu.getpUserID()));
					setProperty("user.name", nu.getUserName());
					setProperty("user.pname", nu.getpUserName());
					setProperty("user.avatar",nu.getThumbUrl());//用户头像-文件名
				}});	
			}

		} catch (AppException e) {
			e.printStackTrace();
		}
		return this.login;
	}
	/**
	 * 清除登录信息
	 */
	public void cleanLoginInfo() {
		this.loginUid = "0";
		this.login = false;
		removeProperty("user.uid","user.pid","user.puid","user.name","user.pname","user.avatar");
	}
	
	/**
	 * 获取登录信息
	 * @return
	 */
	public User getLoginInfo() throws AppException{		
		User u = new User();		
		u.setId(getProperty("user.uid"));
		u.setPid(StringUtils.toInt(getProperty("user.pid")));
		u.setpUserID(getProperty("user.puid"));
		u.setUserName(getProperty("user.name"));
		u.setThumbUrl(getProperty("user.avatar"));
		u.setpUserName(getProperty("user.pname"));
		
		return u;
	}
	
	/**
	 * 保存用户头像
	 * @param fileName
	 * @param bitmap
	 */
	public void saveUserFace(String fileName,Bitmap bitmap) {
		try {
			ImageUtils.saveImage(this, fileName, bitmap);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取用户头像
	 * @param key
	 * @return
	 * @throws AppException
	 */
	public Bitmap getUserFace(String key) throws AppException {
		FileInputStream fis = null;
		try{
			fis = openFileInput(key);
			return BitmapFactory.decodeStream(fis);
		}catch(Exception e){
			throw AppException.run(e);
		}finally{
			try {
				fis.close();
			} catch (Exception e) {}
		}
	}
	
	public boolean containsProperty(String key){
		Properties props = getProperties();
		 return props.containsKey(key);
	}
	
	public void setProperties(Properties ps){
		AppConfig.getAppConfig(this).set(ps);
	}

	public Properties getProperties(){
		return AppConfig.getAppConfig(this).get();
	}
	
	public void setProperty(String key,String value){
		AppConfig.getAppConfig(this).set(key, value);
	}
	
	public String getProperty(String key){
		return AppConfig.getAppConfig(this).get(key);
	}
	public void removeProperty(String...key){
		AppConfig.getAppConfig(this).remove(key);
	}

	public User wechatLogin(String code) throws AppException{
		return ApiClient.wechatLogin(this, code);
	}
	
	
	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	public String sign(String content) {
		return AlipaySignUtils.sign(content, AppConfig.ALIPAY_CONFIG_RSA_PRIVATE);
	}
	
	
	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	public String getAlipayOrderInfo(Order o) {
		// 合作者身份ID
		String orderInfo = "partner=" + "\"" + AppConfig.ALIPAY_CONFIG_PARTNER + "\"";
		// 卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + AppConfig.ALIPAY_CONFIG_SELLER + "\"";
		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + o.getId() + "\"";
		// 商品名称
		orderInfo += "&subject=" + "\"" + o.getProduct().getTitle() + "\"";
		// 商品详情
		orderInfo += "&body=" + "\"" + o.getProduct().getTitle()  + "\"";
		// 商品金额
		orderInfo += "&total_fee=" + "\"" + o.getAmount()+ "\"";
		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + "http://notify.msp.hk/notify.htm"
				+ "\"";
		// 接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";
		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";
		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";
		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"18m\"";
		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";
		// 调用银行卡支付，需配置此参数，参与签名， 固定值
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}	
	
	
	/**
	 * 获取内存中保存图片的路径
	 * @return
	 */
	public String getSaveImagePath() {
		return saveImagePath;
	}
	/**
	 * 设置内存中保存图片的路径
	 * @return
	 */
	public void setSaveImagePath(String saveImagePath) {
		this.saveImagePath = saveImagePath;
	}	
	
}
